﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Message
{
    /// <summary>CCPSIP_016：傳送位置訊息 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。
    /// ChatID = 聊天ID(對方帳號或ClientGID)。
    /// localPID = 發訊方的本機訊息ID。
    /// address = 地址描述。
    /// latitude = 緯度。
    /// longitude = 經度。
    /// hAccuracy = 誤差半徑(公尺)。

    public class send_location : IHttpHandler
    {
        private const string kMsgType = "L";
        private const string kDateTimeFormat = "yyyy/MM/dd HH:mm:ss";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ChatID = req.Form["ChatID"];//聊天ID(對方帳號或ClientGID)
                int localPID = -1;//發訊方的本機訊息ID
                string address = req.Form["address"];//地址描述
                decimal latitude = -1; //緯度
                decimal longitude = -1;//經度
                decimal hAccuracy = -1;//誤差半徑(meter)

                try
                {
                    ChatID = ChatID.Trim();
                    localPID = Convert.ToInt32(req.Form["localPID"]);
                    address = address.Trim();
                    latitude = Math.Round(Convert.ToDecimal(req.Form["latitude"]), 6);
                    longitude = Math.Round(Convert.ToDecimal(req.Form["longitude"]), 6);
                    hAccuracy = Math.Round(Convert.ToDecimal(req.Form["hAccuracy"]), 0);
                }
                catch
                {
                    throw new Exception("Error_01: Parameter Error");//參數錯誤
                }

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_02: Cannot identify this device");//無法識別此裝置
                }


                //【02】組合位置訊息
                //
                string message = string.Format("{0}@{1},{2}", address, latitude, longitude);
                string msgPreview = string.Format("{0} sent you a location.", userInfo.CustomName);


                //【03】儲存訊息
                //
                long MsgID = 0;
                bool isGroupMsg = SipKit.isGroupID(ChatID);

                if (isGroupMsg)
                {
                    if (!OracleKitGroup.isMemberOfGroup(userInfo.SIP_Num, ChatID))
                    {
                        throw new Exception("Error_03: You are not a member");//你不是群組成員
                    }
                    MsgID = OracleKitMsg.InsertGroupMsg(userInfo, ChatID, kMsgType, msgPreview, message, localPID, reqTime);
                }
                else
                {
                    MsgID = OracleKitMsg.InsertMsgOne(userInfo.SIP_Num, ChatID, kMsgType, msgPreview, message, localPID, reqTime);
                }


                //【98】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【99】回傳結果
                //
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                resultDict["MsgID"] = Convert.ToString(MsgID);
                resultDict["MsgTime"] = reqTime.ToString(kDateTimeFormat);
                resultDict["LocalPID"] = Convert.ToString(localPID);

                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
